Date: 2016-09-26


In [53]:
%matplotlib inline
%reload_ext autoreload
%autoreload 2
%qtconsole
import os
import sys
import collections
import random
import itertools
import functools
import scipy.fftpack
import scipy.signal
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as clr
import matplotlib.patches as patches
import seaborn as sns
import pandas as pd
import tqdm
import dask
import dask.multiprocessing

sys.path.append('../src/')
import data_filter
import ripples
import spectral

Testing PETH plotting


In [2]:
def sim_poisson(rate, sampling_frequency=1000):
    y = np.random.uniform(size=rate.shape) <= (rate / sampling_frequency);
    return y.astype(int)

sampling_frequency = 1500
window_offset = (-0.500, 0.500)
num_trials = 500
before_zero_firing_rate = 1
after_zero_firing_rate = 10

num_time_points = ((window_offset[1] - window_offset[0]) * sampling_frequency) + 1
time = np.linspace(window_offset[0], window_offset[1], num=num_time_points)
time_before_zero_ind = np.where(time < 0)
time_after_zero_ind = np.where(time >= 0)
rate = np.concatenate((before_zero_firing_rate * np.ones((time_before_zero_ind[0].size, num_trials), float),
                       after_zero_firing_rate * np.ones((time_after_zero_ind[0].size, num_trials), float)),
                      axis=0)
spikes = sim_poisson(rate, sampling_frequency=1500)
simulated_spike_times = time[spikes.nonzero()[0]]

In [3]:
bin_size = 0.025 # in seconds
spike_times = time[spikes.nonzero()[0]]
number_of_bins = np.fix((window_offset[1] - window_offset[0]) / bin_size).astype(int)
bin_count, bins = np.histogram(spike_times, bins=number_of_bins)

rate = bin_count / (bin_size * num_trials)
plt.plot(bins[:-1] + (bin_size / 2), rate)
plt.axhline(before_zero_firing_rate, color='black', linestyle=':')
plt.axhline(after_zero_firing_rate, color='black', linestyle=':')
plt.axvline(0, color='black', linestyle=':')
plt.xlim(window_offset)


Out[3]:
(-0.5, 0.5)

In [4]:
def peri_event_time_histogram(spike_times, time_extent,
                              number_of_trials=1, bin_size=0.025,
                              normalized=False):
    ''' Returns the histogram of spike times
    
    Parameters:
        spike_times: An indicator array with the time of spikes
        time_extent: A tuple of start and end time of the time period
                     under consideration
        bin_size: The size of the histogram time bins. Must be in the
                  same units as the time extent
        normalized: boolean where True means the firing rate is normalized
                    by its maximum firing rate
                     
    Returns:
        rate: The firing rate for each bin
        bins: The left edge of each histogram time bin
    '''
    number_of_bins = np.fix((time_extent[1] - time_extent[0]) / bin_size).astype(int)
    bin_count, bins = np.histogram(spike_times, bins=number_of_bins, range=time_extent)
    rate = bin_count / (bin_size * number_of_trials)
    if normalized:
        rate = rate / rate.max()
        
    return rate, bins


window_offset = (-0.500, 0.500)
spike_times = time[spikes.nonzero()[0]]
rate, bins = peri_event_time_histogram(spike_times, window_offset,
                                       number_of_trials=num_trials)

fig = plt.figure

ax1 = plt.subplot(2,1,1)
ax1.bar(bins[:-1], rate, width=0.025)
ax1.axhline(before_zero_firing_rate, color='black', linestyle=':')
ax1.axhline(after_zero_firing_rate, color='black', linestyle=':')
ax1.axvline(0, color='black', linestyle=':')
ax1.set_xlim(window_offset)

rate, bins = peri_event_time_histogram(spike_times, window_offset,
                                       number_of_trials=num_trials,
                                       bin_size=0.100)

ax2 = plt.subplot(2,1,2)
ax2.bar(bins[:-1], rate, width=0.100)
ax2.axhline(before_zero_firing_rate, color='black', linestyle=':')
ax2.axhline(after_zero_firing_rate, color='black', linestyle=':')
ax2.axvline(0, color='black', linestyle=':')
ax2.set_xlim(window_offset)


Out[4]:
(-0.5, 0.5)

In [5]:
def plot_peri_event_time_histogram(spike_times, time_extent, normalized=False,
                                   number_of_trials=1, bin_size=0.025,
                                   color=None, axlabel=None,
                                   label=None, ax=None, rug=False):
    if ax is None:
        ax = plt.gca()
    if color is None:
        line, = ax.plot(spikes.mean(), 0)
        color = line.get_color()
        line.remove()

    rate, bins = peri_event_time_histogram(spike_times, time_extent,
                                           number_of_trials=number_of_trials,
                                           bin_size=bin_size,
                                           normalized=normalized)
    ax.bar(bins[:-1], rate,
           width=bin_size,
           edgecolor=color,
           linewidth=2,
           fill=False)
    if rug:
        sns.rugplot(spike_times, ax=ax, color=color, alpha=0.4)

spike_times = time[spikes.nonzero()[0]]
plot_peri_event_time_histogram(spike_times, window_offset,
                               number_of_trials=num_trials,
                               bin_size=0.025,
                               color='green', rug=True)
plt.axhline(before_zero_firing_rate, color='black', linestyle=':')
plt.axhline(after_zero_firing_rate, color='black', linestyle=':')
plt.axvline(0, color='black', linestyle=':')
plt.xlim(window_offset)


Out[5]:
(-0.5, 0.5)

In [6]:
plot_peri_event_time_histogram(spike_times, window_offset,
                               number_of_trials=num_trials, bin_size=0.050)
plt.axhline(before_zero_firing_rate, color='black', linestyle=':')
plt.axhline(after_zero_firing_rate, color='black', linestyle=':')
plt.axvline(0, color='black', linestyle=':')
plt.xlim(window_offset)


Out[6]:
(-0.5, 0.5)

In [7]:
plot_peri_event_time_histogram(spike_times, window_offset,
                               number_of_trials=num_trials, bin_size=0.050,
                               normalized=True)
plt.axvline(0, color='black', linestyle=':')
plt.xlim(window_offset)


Out[7]:
(-0.5, 0.5)

Ripple Triggered PETH

Multitaper-defined ripples


In [106]:
Animal = collections.namedtuple('Animal', {'directory', 'short_name'})
num_days = 8
days = range(1, num_days + 1)
animals = {'HPa': Animal(directory='HPa_direct', short_name='HPa')}

epoch_info = data_filter.make_epochs_dataframe(animals, days)
tetrode_info = data_filter.make_tetrode_dataframe(animals)
epoch_keys = data_filter.get_dataframe_index(epoch_info
    .loc[(['HPa'], [8]), :]
    .loc[epoch_info.environment == 'wtr1'])

cur_tetrode_info = pd.concat([tetrode_info[key] for key in epoch_keys])
cur_tetrode_info


Out[106]:
area depth descrip numcells tetrode_id
animal day epoch_ind tetrode_number
HPa 8 2 1 CA1 113 riptet 12 HPa821
2 CA1 121 NaN 0 HPa822
3 CA1 90 CA1Ref 0 HPa823
4 CA1 116 riptet 15 HPa824
5 CA1 116 riptet 0 HPa825
6 CA1 110 riptet 0 HPa826
7 CA1 114 riptet 0 HPa827
8 iCA1 114 riptet 0 HPa828
9 iCA1 100 riptet 0 HPa829
10 iCA1 96 NaN 0 HPa8210
11 iCA1 106 riptet 0 HPa8211
12 iCA1 114 riptet 3 HPa8212
13 iCA1 120 NaN 0 HPa8213
14 iCA1 105 riptet 6 HPa8214
15 PFC 93 NaN 0 HPa8215
16 PFC 90 NaN 0 HPa8216
17 PFC 90 NaN 6 HPa8217
18 PFC 90 NaN 0 HPa8218
19 PFC 130 NaN 0 HPa8219
20 PFC 109 NaN 0 HPa8220

In [9]:
neuron_info = data_filter.make_neuron_dataframe(animals)
cur_neuron_info = pd.concat([neuron_info[key] for key in epoch_keys]).dropna().query('numspikes > 0')
cur_neuron_info


Out[9]:
area csi meanrate numspikes propbursts spikewidth neuron_id
animal day epoch_ind tetrode_number neuron_number
HPa 8 2 1 2 CA1 0.05963302752293578 0.7218543046357616 872 0.2305045871559633 10.359959504215627 HPa8212
3 CA1 0.19162790697674417 0.8899006622516556 1075 0.6409302325581395 7.624190000134791 HPa8213
4 CA1 0.08121019108280254 0.5198675496688742 628 0.3200636942675159 10.734931880073724 HPa8214
5 CA1 0.14817320703653586 2.447019867549669 2956 0.4983085250338295 9.1987074003374 HPa8215
6 CA1 0.1690929451287794 0.7392384105960265 893 0.5442329227323628 9.028117472746398 HPa8216
7 CA1 0.053475935828877004 0.15480132450331127 187 0.20855614973262032 11.719632986962303 HPa8217
4 1 CA1 0.09773936170212766 1.2450331125827814 1504 0.3184840425531915 10.573569863065767 HPa8241
2 CA1 0.13846153846153847 1.1837748344370862 1430 0.4951048951048951 8.249598508446987 HPa8242
3 CA1 0.1411764705882353 0.7740066225165563 935 0.48128342245989303 9.473909850454165 HPa8243
4 CA1 0.11428571428571428 0.23178807947019867 280 0.2892857142857143 7.821072138691519 HPa8244
5 CA1 0.04081632653061224 0.20281456953642385 245 0.09387755102040816 8.26724220794418 HPa8245
6 CA1 0.02981651376146789 0.3609271523178808 436 0.10550458715596331 13.34939605009777 HPa8246
7 CA1 0.16352201257861634 0.1316225165562914 159 0.5471698113207547 8.622862142764975 HPa8247
8 CA1 0.16104868913857678 0.22102649006622516 267 0.43820224719101125 9.926903553501516 HPa8248
12 1 iCA1 0.02631578947368421 0.06291390728476821 76 0.07894736842105263 8.965920269909438 HPa82121
2 iCA1 0.04430379746835443 0.3923841059602649 474 0.1962025316455696 10.073373561223226 HPa82122
3 iCA1 0.053717494811378344 6.780629139072848 8191 0.1947259186912465 5.81454456934001 HPa82123
14 1 iCA1 0.06834268977300463 3.3915562913907285 4097 0.24969489870637052 11.11293649893477 HPa82141
2 iCA1 0.07884972170686456 2.6771523178807946 3234 0.2786023500309215 10.208434221893334 HPa82142
3 iCA1 0.048678720445062586 0.5951986754966887 719 0.22253129346314326 8.64379513034075 HPa82143
6 iCA1 0.09302325581395349 0.10678807947019868 129 0.3643410852713178 7.082362239433368 HPa82146
17 1 PFC 0.014189693801344288 1.1084437086092715 1339 0.06572068707991038 10.417261378112482 HPa82171
3 PFC 0 0.16473509933774835 199 0 12.93298222642811 HPa82173
4 PFC 0.008634868421052632 2.013245033112583 2432 0.029605263157894735 8.619500395429855 HPa82174
5 PFC 0.00519311911716975 2.5504966887417218 3081 0.023044466082440766 10.821009588390197 HPa82175
6 PFC 0.004267668146124957 9.698675496688741 11716 0.014595425059747353 12.333565861353105 HPa82176

In [10]:
data_filter.get_spikes_dataframe(cur_neuron_info.index[1], animals)


Out[10]:
is_spike
time
2713.1716 1
2713.9817 1
2715.5873 1
2715.5928 1
2715.5987 1
2715.6064 1
2715.6126 1
2730.9728 1
2732.0596 1
2732.0648 1
2772.1994 1
2783.8786 1
2783.8845 1
2809.8635 1
2809.9833 1
2809.9872 1
2809.9918 1
2810.1568 1
2810.1605 1
2810.1689 1
2810.5955 1
2810.5994 1
2810.8661 1
2810.8701 1
2810.8749 1
2811.7259 1
2811.7367 1
2811.7409 1
2811.7589 1
2812.2599 1
... ...
3868.4349 1
3869.9888 1
3871.0561 1
3871.0597 1
3871.5105 1
3871.5530 1
3872.1288 1
3872.2858 1
3872.2898 1
3872.5120 1
3872.5192 1
3872.8088 1
3872.9790 1
3874.8630 1
3875.5539 1
3875.6993 1
3875.7030 1
3875.7193 1
3917.1300 1
3917.1341 1
3917.5343 1
3917.6665 1
3917.8715 1
3917.9622 1
3917.9882 1
3918.0120 1
3918.0400 1
3918.1475 1
3919.3231 1
3919.6541 1

1075 rows × 1 columns


In [11]:
cur_tetrode_info = pd.concat([tetrode_info[key] for key in epoch_keys])
tetrode_index = data_filter.get_dataframe_index(cur_tetrode_info)
lfp_data = data_filter.get_LFP_data(tetrode_index, animals)
segments_multitaper = np.load('segments_multitaper.npy')
merged_segments = list(ripples.merge_ranges([seg for tetrode in segments_multitaper
                                         for seg in tetrode]))

speed_threshold = 4
position_dataframe = data_filter.get_position_dataframe(epoch_keys, animals)[0]
interpolated_position = (pd.concat([lfp_data[0], position_dataframe])
                            .sort_index()
                            .interpolate(method='linear')
                            .reindex(lfp_data[0].index))

average_speed = np.array([interpolated_position.loc[segment_start:segment_end, :].smoothed_speed.mean()
                 for segment_start, segment_end in merged_segments])
ripple_times = [merged_segments[i] for i in np.where(average_speed <= speed_threshold)[0]]

In [12]:
window_offset = (-0.500, 0.500)
spikes_data = [data_filter.get_spikes_dataframe(neuron_ind, animals)
               for neuron_ind in cur_neuron_info.index]
spike_segments = list(ripples.reshape_to_segments(spikes_data, ripple_times, window_offset))




In [13]:
def get_spike_times(spike_dataframe):
    return spike_dataframe.reset_index().time.values

number_of_trials = len(ripple_times)
spike_times = get_spike_times(spike_segments[0])

plot_peri_event_time_histogram(spike_times, window_offset,
                               number_of_trials=number_of_trials,
                               bin_size=0.025,
                               rug=True)
plt.xlim(window_offset)


Out[13]:
(-0.5, 0.5)

In [14]:
neuron_labels = cur_neuron_info.set_index(['area', 'neuron_id'], append=True).index
labeled_spike_segments = pd.concat(spike_segments,
                                   keys=neuron_labels,
                                   names=neuron_labels.names)
labeled_spike_segments


Out[14]:
is_spike
animal day epoch_ind tetrode_number neuron_number area neuron_id segment_number segment_start segment_end time
HPa 8 2 1 2 CA1 HPa8212 1 2794.348845 2794.372845 -0.2121 1
-0.2012 1
-0.1944 1
-0.1904 1
-0.0690 1
-0.0648 1
-0.0604 1
-0.0547 1
0.1062 1
2 2794.628845 2794.652845 -0.4921 1
-0.4812 1
-0.4744 1
-0.4704 1
-0.3490 1
-0.3448 1
-0.3404 1
-0.3347 1
-0.1738 1
3 2795.676846 2795.740846 0.0142 1
0.0293 1
0.1280 1
0.1701 1
4 2796.032846 2796.056846 -0.3418 1
-0.3267 1
-0.2280 1
-0.1859 1
0.3784 1
0.3919 1
0.4065 1
0.4260 1
1 2 CA1 HPa8212 4 2796.032846 2796.056846 ... ...
1 2 CA1 HPa8212 4 2796.032846 2796.056846 ... 1
... 1
0.2202 1
16 3428.169195 3428.189195 0.3888 1
0.4172 1
-0.4151 1
-0.1798 1
-0.0112 1
0.0172 1
17 3428.569195 3428.597195 0.1061 1
0.2261 1
-0.3729 1
-0.2960 1
-0.1825 1
-0.0671 1
-0.0108 1
0.0712 1
0.1071 1
0.3381 1
18 3609.393295 3609.409295 0.4008 1
0.4808 1
-0.4862 1
-0.4233 1
-0.4184 1
-0.1735 1
-0.0758 1
-0.0022 1
0.1898 1
0.2708 1
0.3123 1

629 rows × 1 columns


In [15]:
def peth_wrap(time_extent, number_of_trials, **kwargs):
    dataframe = kwargs.pop('data')
    spike_times = get_spike_times(dataframe)
    plot_peri_event_time_histogram(spike_times, time_extent,
                                   number_of_trials=number_of_trials,
                                   **kwargs)

grid = sns.FacetGrid(labeled_spike_segments.reset_index(), col='neuron_id', col_wrap=5, hue='area')
grid.map_dataframe(peth_wrap, window_offset, len(ripple_times), rug=True)
grid.set(xlim=window_offset);
grid.add_legend();
grid.map(plt.axvline, x=0, color='black', ls=':')


Out[15]:
<seaborn.axisgrid.FacetGrid at 0x118bf0cc0>

In [16]:
grid = sns.FacetGrid(labeled_spike_segments.reset_index(), col='neuron_id', col_wrap=5, hue='area')
grid.map_dataframe(peth_wrap, window_offset, len(ripple_times), bin_size=0.050, rug=True)
grid.set(xlim=window_offset);
grid.add_legend();
grid.map(plt.axvline, x=0, color='black', ls=':')


Out[16]:
<seaborn.axisgrid.FacetGrid at 0x118d532e8>

In [17]:
def compute_population_dataframe(x, time_extent, **kwargs):
    rate, bins = peri_event_time_histogram(x.time, time_extent,
                                           **kwargs)
    
    result = {'rate': rate, 'time': bins[:-1], 'area': x.area.iloc[0]}
    return pd.DataFrame(result)

def compute_population_rate(spike_dataframe, time_extent, number_of_trials=1):
    return (spike_dataframe
              .reset_index()
              .groupby('neuron_id')
              .apply(compute_population_dataframe, time_extent,
                     number_of_trials=len(ripple_times),
                     normalized=True,
                     )
              .groupby(['area', 'time'])
              .mean())

population_rate = compute_population_rate(labeled_spike_segments, window_offset, len(ripple_times))
grid = sns.FacetGrid(population_rate.reset_index(),
                     col='area', col_wrap=5, hue='area',
                     col_order=['CA1', 'iCA1', 'PFC'],
                     hue_order=['CA1', 'iCA1', 'PFC'])
grid.map(plt.bar, 'time', 'rate', width=0.025,
         linewidth=2)
grid.map(plt.axvline, x=0, color='black', ls=':')
grid.set(xlim=window_offset)


Out[17]:
<seaborn.axisgrid.FacetGrid at 0x119937400>

Their Ripples


In [18]:
frank_individual_ripple_times = [ripples._get_computed_ripple_times(tetrode_tuple, animals)
                                 for tetrode_tuple in data_filter.get_dataframe_index(cur_tetrode_info[cur_tetrode_info.area == 'CA1'])]
merged_frank_segments = list(ripples.merge_ranges([seg for tetrode in frank_individual_ripple_times
                                         for seg in tetrode]))

speed_threshold = 4
interpolated_position = (pd.concat([lfp_data[0], position_dataframe])
                            .sort_index()
                            .interpolate(method='linear')
                            .reindex(lfp_data[0].index))

frank_average_speed = np.array([interpolated_position.loc[segment_start:segment_end, :].smoothed_speed.mean()
                                for segment_start, segment_end in merged_frank_segments])
frank_ripple_times = [merged_frank_segments[i] for i in np.where(frank_average_speed <= speed_threshold)[0]]


window_offset  = (-0.500, 0.500)
spikes_data = [data_filter.get_spikes_dataframe(neuron_ind, animals)
               for neuron_ind in cur_neuron_info.index]
frank_spike_segments = list(ripples.reshape_to_segments(spikes_data, frank_ripple_times, window_offset))




In [19]:
neuron_labels = cur_neuron_info.set_index(['area', 'neuron_id'], append=True).index
frank_labeled_spike_segments = pd.concat(frank_spike_segments,
                                         keys=neuron_labels,
                                         names=neuron_labels.names)

In [20]:
grid = sns.FacetGrid(frank_labeled_spike_segments.reset_index(), col='neuron_id', col_wrap=5, hue='area')
grid.map_dataframe(peth_wrap, window_offset, len(frank_ripple_times), rug=True)
grid.set(xlim=window_offset);
grid.add_legend();
grid.map(plt.axvline, x=0, color='black', ls=':')


Out[20]:
<seaborn.axisgrid.FacetGrid at 0x1203c2cf8>

In [21]:
grid = sns.FacetGrid(frank_labeled_spike_segments.reset_index(), col='neuron_id', col_wrap=5, hue='area')
grid.map_dataframe(peth_wrap, window_offset, len(frank_ripple_times), rug=True, bin_size=0.050)
grid.set(xlim=window_offset);
grid.add_legend();
grid.map(plt.axvline, x=0, color='black', ls=':')


Out[21]:
<seaborn.axisgrid.FacetGrid at 0x11f44a358>

In [22]:
grid = sns.FacetGrid(frank_labeled_spike_segments.reset_index(), col='neuron_id', col_wrap=5, hue='area')
grid.map_dataframe(peth_wrap, window_offset, len(frank_ripple_times), rug=True, bin_size=0.050, normalized=True)
grid.set(xlim=window_offset);
grid.add_legend();
grid.map(plt.axvline, x=0, color='black', ls=':')


Out[22]:
<seaborn.axisgrid.FacetGrid at 0x165d4fb38>

In [23]:
population_rate = compute_population_rate(frank_labeled_spike_segments, window_offset, len(frank_ripple_times))
grid = sns.FacetGrid(population_rate.reset_index(),
                     col='area', col_wrap=5, hue='area',
                     col_order=['CA1', 'iCA1', 'PFC'],
                     hue_order=['CA1', 'iCA1', 'PFC'])
grid.map(plt.bar, 'time', 'rate', width=0.025,
         linewidth=2)
grid.map(plt.axvline, x=0, color='black', ls=':')
grid.set(xlim=window_offset)


Out[23]:
<seaborn.axisgrid.FacetGrid at 0x1872d94e0>

Ripple Spectrum


In [33]:
ripple_df = (pd.DataFrame({'time': np.array(ripple_times)[:, 0], 'is_ripple': 1})
              .set_index('time')
              .reindex(index=lfp_data[0].index.values,
                       tolerance=0.0001,
                       method='nearest',
                       fill_value=0))

print(ripple_df)
print(ripple_df[ripple_df.is_ripple == 1])


             is_ripple
time                  
2712.994800          0
2712.995467          0
2712.996133          0
2712.996800          0
2712.997467          0
2712.998133          0
2712.998800          0
2712.999467          0
2713.000133          0
2713.000800          0
2713.001467          0
2713.002133          0
2713.002800          0
2713.003467          0
2713.004133          0
2713.004800          0
2713.005467          0
2713.006133          0
2713.006800          0
2713.007467          0
2713.008133          0
2713.008800          0
2713.009467          0
2713.010133          0
2713.010800          0
2713.011467          0
2713.012133          0
2713.012800          0
2713.013467          0
2713.014133          0
...                ...
3919.994133          0
3919.994800          0
3919.995467          0
3919.996133          0
3919.996800          0
3919.997467          0
3919.998133          0
3919.998800          0
3919.999467          0
3920.000133          0
3920.000800          0
3920.001467          0
3920.002133          0
3920.002800          0
3920.003467          0
3920.004133          0
3920.004800          0
3920.005467          0
3920.006133          0
3920.006800          0
3920.007467          0
3920.008133          0
3920.008800          0
3920.009467          0
3920.010133          0
3920.010800          0
3920.011467          0
3920.012133          0
3920.012800          0
3920.013467          0

[1810528 rows x 1 columns]
             is_ripple
time                  
2794.348845          1
2794.628845          1
2795.676846          1
2796.032846          1
2796.896846          1
2834.652867          1
2848.180875          1
2849.708876          1
2954.932934          1
3178.153057          1
3217.517079          1
3221.017081          1
3226.305084          1
3305.249127          1
3389.725174          1
3428.169195          1
3428.569195          1
3609.393295          1
3849.041427          1

In [49]:
ripple_spectrum = pd.DataFrame(spectral.multitaper_power_spectral_density(ripple_df.is_ripple.values,
                                                                          1500,
                                                                          time_halfbandwidth_product=1,
                                                                          number_of_tapers=20,
                                                                          desired_frequencies=[0, 10]))
ripple_spectrum.plot(x='frequency', y='power')


Out[49]:
<matplotlib.axes._subplots.AxesSubplot at 0x1a6ba7b00>

In [48]:
ripple_spectrum = pd.DataFrame(spectral.multitaper_power_spectral_density(ripple_df.is_ripple.values,
                                                                          1500,
                                                                          time_halfbandwidth_product=1,
                                                                          number_of_tapers=20,
                                                                          desired_frequencies=[0, 1]))
ripple_spectrum.plot(x='frequency', y='power')


Out[48]:
<matplotlib.axes._subplots.AxesSubplot at 0x1a88e5668>

In [35]:
frank_ripple_df = (pd.DataFrame({'time': np.array(frank_ripple_times)[:, 0], 'is_ripple': 1})
              .set_index('time')
              .reindex(index=lfp_data[0].index.values,
                       tolerance=0.0001,
                       method='nearest',
                       fill_value=0))

print(frank_ripple_df)
print(frank_ripple_df[frank_ripple_df.is_ripple == 1])


             is_ripple
time                  
2712.994800          0
2712.995467          0
2712.996133          0
2712.996800          0
2712.997467          0
2712.998133          0
2712.998800          0
2712.999467          0
2713.000133          0
2713.000800          0
2713.001467          0
2713.002133          0
2713.002800          0
2713.003467          0
2713.004133          0
2713.004800          0
2713.005467          0
2713.006133          0
2713.006800          0
2713.007467          0
2713.008133          0
2713.008800          0
2713.009467          0
2713.010133          0
2713.010800          0
2713.011467          0
2713.012133          0
2713.012800          0
2713.013467          0
2713.014133          0
...                ...
3919.994133          0
3919.994800          0
3919.995467          0
3919.996133          0
3919.996800          0
3919.997467          0
3919.998133          0
3919.998800          0
3919.999467          0
3920.000133          0
3920.000800          0
3920.001467          0
3920.002133          0
3920.002800          0
3920.003467          0
3920.004133          0
3920.004800          0
3920.005467          0
3920.006133          0
3920.006800          0
3920.007467          0
3920.008133          0
3920.008800          0
3920.009467          0
3920.010133          0
3920.010800          0
3920.011467          0
3920.012133          0
3920.012800          0
3920.013467          0

[1810528 rows x 1 columns]
             is_ripple
time                  
2715.702135          1
2723.397472          1
2725.924807          1
2726.120807          1
2731.782810          1
2737.026147          1
2737.128813          1
2737.187480          1
2742.834816          1
2743.261483          1
2748.270819          1
2751.050821          1
2751.155488          1
2751.318155          1
2751.822821          1
2752.852155          1
2753.203489          1
2753.676156          1
2753.726822          1
2754.348823          1
2754.971490          1
2758.621492          1
2760.647493          1
2760.760826          1
2762.726827          1
2763.138828          1
2763.634161          1
2763.930161          1
2764.021495          1
2764.694829          1
...                ...
3895.122120          1
3901.112790          1
3901.594790          1
3903.312124          1
3903.693458          1
3903.924124          1
3904.514791          1
3904.769458          1
3904.948125          1
3905.272792          1
3906.410126          1
3906.521459          1
3906.924793          1
3907.206126          1
3907.593460          1
3907.963460          1
3908.910794          1
3909.057461          1
3909.363461          1
3910.710128          1
3911.079462          1
3911.151462          1
3911.700795          1
3912.839463          1
3913.226796          1
3913.923463          1
3914.190797          1
3914.310797          1
3919.105466          1
3919.222800          1

[221 rows x 1 columns]

In [50]:
frank_ripple_spectrum = pd.DataFrame(spectral.multitaper_power_spectral_density(frank_ripple_df.is_ripple.values,
                                                                                1500,
                                                                                time_halfbandwidth_product=1,
                                                                                number_of_tapers=20,
                                                                                desired_frequencies=[0, 10]))
frank_ripple_spectrum.plot(x='frequency', y='power')


Out[50]:
<matplotlib.axes._subplots.AxesSubplot at 0x1a7381c88>

In [188]:
frank_ripple_spectrum = pd.DataFrame(spectral.multitaper_power_spectral_density(frank_ripple_df.is_ripple.values - frank_ripple_df.is_ripple.values.mean(),
                                                                                1500,
                                                                                time_halfbandwidth_product=1,
                                                                                number_of_tapers=20,
                                                                                desired_frequencies=[0, 1]))
frank_ripple_spectrum.plot(x='frequency', y='power')


Out[188]:
<matplotlib.axes._subplots.AxesSubplot at 0x28c8c5358>

Normalized Ripple Triggered Average

Non-normalized


In [61]:
window_of_interest = (-3.000, 3.000)
time_of_interest_lfp_segments = list(ripples.reshape_to_segments(lfp_data, ripple_times,
                                                                 window_of_interest))

ripple_triggered_average = [lfp.reset_index().groupby('time').electric_potential.mean()
                             for lfp in time_of_interest_lfp_segments]
num_lfps = len(ripple_triggered_average)

fig, axis_handles = plt.subplots(num_lfps, 1, figsize=(12, 9), sharex=True)

# LFP
for ind in range(0, num_lfps):
    ripple_triggered_average[ind].plot(ax=axis_handles[ind], legend=False)
    axis_handles[ind].axvline(0, color='black')
    axis_handles[ind].set_ylim((ripple_triggered_average[ind].min(),
                                ripple_triggered_average[ind].max()))
    axis_handles[ind].set_ylabel(spectral.tetrode_title(tetrode_index[ind], cur_tetrode_info),
                                 horizontalalignment='right',
                                 rotation='horizontal')



One tetrode - each ripple


In [141]:
print(cur_tetrode_info.iloc[14])
grid = sns.FacetGrid(time_of_interest_lfp_segments[14].reset_index(),
                     row='segment_number',
                     size=0.8,
                     aspect=18)
grid.map(plt.plot, 'time', 'electric_potential')
grid.map(plt.axvline, x=0, color='black', ls=':')


area              PFC
depth              93
descrip           NaN
numcells            0
tetrode_id    HPa8215
Name: (HPa, 8, 2, 15), dtype: object
Out[141]:
<seaborn.axisgrid.FacetGrid at 0x27e1c2198>

In [142]:
print(cur_tetrode_info.iloc[15])
grid = sns.FacetGrid(time_of_interest_lfp_segments[15].reset_index(),
                     row='segment_number',
                     size=0.8,
                     aspect=18)
grid.map(plt.plot, 'time', 'electric_potential')
grid.map(plt.axvline, x=0, color='black', ls=':')


area              PFC
depth              90
descrip           NaN
numcells            0
tetrode_id    HPa8216
Name: (HPa, 8, 2, 16), dtype: object
Out[142]:
<seaborn.axisgrid.FacetGrid at 0x27db69d30>

Random segment of trial


In [186]:
fig, axis_handles = plt.subplots(1, 1, figsize=(15, 3), sharex=True)
sample_time = random.sample(set(lfp_data[0].index.values), 1)[0]
for ind in np.arange(14, 20):
    lfp_data[ind].loc[sample_time:sample_time+6].plot(ax=axis_handles)


Normalized


In [129]:
window_of_interest = (-3.000, 3.000)
time_of_interest_lfp_segments = list(ripples.reshape_to_segments(lfp_data, ripple_times,
                                                                 window_of_interest))

def normalize_0_1(x):
    '''Normalized between 0 and 1'''
    return (x - x.min()) / (x.max() - x.min())

def normalize_ripple_lfp(dataframe):
    return (dataframe
             .reset_index('segment_number')
             .groupby('segment_number')
                 .transform(normalize_0_1)
             .reset_index('time')
             .groupby('time')
             .mean())
    

ripple_triggered_average = [normalize_ripple_lfp(lfp)
                            for lfp in time_of_interest_lfp_segments]
num_lfps = len(ripple_triggered_average)

fig, axis_handles = plt.subplots(num_lfps, 1, figsize=(12, 9), sharex=True)

# LFP
for ind in range(0, num_lfps):
    ripple_triggered_average[ind].plot(ax=axis_handles[ind], legend=False)
    axis_handles[ind].axvline(0, color='black')
    axis_handles[ind].set_ylim((0.4, 0.6))
    axis_handles[ind].set_ylabel(spectral.tetrode_title(tetrode_index[ind], cur_tetrode_info),
                                 horizontalalignment='right',
                                 rotation='horizontal')




In [128]:
tetrode_labels = cur_tetrode_info.set_index(['area', 'tetrode_id'], append=True).index
labeled_ripple_triggered_average = pd.concat(ripple_triggered_average,
                                   keys=tetrode_labels,
                                   names=tetrode_labels.names)

grid = sns.FacetGrid(labeled_ripple_triggered_average.reset_index(),
                     row='tetrode_id',
                     hue='area',
                     size=0.8,
                     aspect=18)
grid.map(plt.plot, 'time', 'electric_potential')
grid.map(plt.axvline, x=0, color='black', ls=':')


Out[128]:
<seaborn.axisgrid.FacetGrid at 0x2686563c8>

In [ ]: